import React from 'react';
import moment from 'moment';
import './Comment.css';

export default class CommentForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            name: "",
            content: ""
        }
        this.handlerSubmit = this.handlerSubmit.bind(this);
        this.handlerName = this.handlerName.bind(this);
        this.handlerContent = this.handlerContent.bind(this);
    }

    handlerSubmit(event) {
        event.preventDefault();
        const uuid = this.guid();
        const { content } = this.state;
        const name = this.state.name || 'SPRONG';
        if (!content) {
            alert('content 不允许为空');
            return;
        }
        if (this.props.addComment) {
            this.props.addComment({
                content,
                name,
                id: uuid,
                date: moment().format('YYYY-MM-DD HH:mm:ss')
            });
        }
        this.setState({name:"", content:""});
    }

    handlerName(event) {
        const { content } = this.state;
        this.setState({
            name: event.target.value,
            content: content
        });
    }

    handlerContent(event) {
        const { name } = this.state;
        this.setState({
            name: name,
            content: event.target.value
        });
    }

    guid() {
        function S4() {
            return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        }
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    render() {
        return (
            <div className="commentForm">
                <form onSubmit={this.handlerSubmit}>
                    <div>
                        <label>姓名: <input type="text" placeholder="姓名" value={this.state.name} onChange={this.handlerName}/></label>
                    </div>
                    <div style={{margin: "10px 0"}}>
                        <label>内容: <input value={this.state.content} onChange={this.handlerContent}/></label>
                    </div>
                    <div>
                        <input className="sub-btn" type="submit" value="评论"/>
                    </div>
                </form>
            </div>
        );
    }
}